/**自定义404类 */
const createError = require('http-errors');
const multer = require('multer');
const logger = require('./logger');

const success = ({ res, data = {}, message = '请求成功', code = 200 }) => {
  res.status(code).json({ data: data, message: message, status: true });
};
const failure = ({ res, error, data = {}, message = '服务器错误', code = 500 }) => {
  if (error.name === 'SequelizeValidationError') {
    message = error.errors.map((e) => e.message);
    code = 400;
  } else if (error instanceof createError.HttpError) {
    // http-errors 库创建的错误
    code = error.status;
    message = error.message;
  } else if (error instanceof multer.MulterError) {
    if (error.code === 'LIMIT_FILE_SIZE') {
      code = 413;
      message = '文件大小超出限制。';
    } else {
      code = 400;
      message = error.message;
    }
  } else {
    // 其他未知错误

    logger.error('服务器错误：', error);
  }

  res.status(code).json({
    data,
    status: false,
    errors: error.name,
    message: Array.isArray(message) ? message : [message],
  });
};

module.exports = {
  success,
  failure,
};
